{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 数据准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = np.array([[0, 1], [1, 1]])\n",
    "Y= np.array([[0, 0]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 矩阵计算基础\n",
    "对于标量而言，计算两样本之间的距离很简单：$dist=\\sqrt{a^{2}+b^{2}}$。而在矩阵情况下，为了避免循环加速计算，需要充分利用向量运算的性质。\n",
    "\n",
    "首先不难得到，对于计算$A$与$B$两矩阵中两两样本的距离，其距离矩阵的维度为$(n\\_samples\\_A, n\\_samples\\_B)$。想到使用公式$(a-b)^{2}=a^{2}-2ab-b^{2}$，矩阵形式下的公式为：\n",
    "\n",
    "$$\n",
    "dist(A, B)=A^{2}-2A{\\cdot}B^{T}+B^{2}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1.        ]\n",
      " [1.41421356]]\n"
     ]
    }
   ],
   "source": [
    "res_dist=np.dot(X,Y.T)    # 易得最终的距离矩阵维度为(len(X),len(Y))\n",
    "\n",
    "X_squared=np.sum(np.square(X),axis=1).reshape((res_dist.shape[0],-1))\n",
    "Y_squared=np.sum(np.square(Y),axis=1).reshape((-1,res_dist.shape[1]))\n",
    "\n",
    "res_dist=np.sqrt(X_squared-2*res_dist+Y_squared)\n",
    "print(res_dist)"
   ]
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
